<template>
  <ToolbarButton
    type="dropdown"
    icon="i-mdi-margin"
    title="页边距"
    dropdown-icon="i-ri-arrow-down-s-fill"
    popover-width="320px"
    popover-placement="bottom-start"
    :large-icon="props.largeIcon"
    :hide-text="props.hideText"
    @main-click="togglePageMargin"
  >
    <template #dropdown>
      <div class="page-margin-dropdown">
        <!-- 页边距选项 -->
        <div class="page-margin-options">
          <div
            v-for="(option, index) in marginOptions"
            :key="index"
            class="page-margin-option"
            :class="{ active: currentMarginOption === option }"
            @click="setPageMargin(option.margin)"
          >
            <!-- 选中标记 -->
            <div class="page-margin-check">
              <i
                v-if="currentMarginOption === option"
                class="i-ri-check-line"
              ></i>
            </div>
            <!-- 预览区域 -->
            <div class="page-margin-preview">
              <!-- 外框（白色背景，有边框） -->
              <div class="preview-frame">
                <!-- 上边距线（等高线，横跨整个宽度） -->
                <div
                  class="margin-line margin-top"
                  :style="{
                    top: `${getPreviewOffset(option.margin.top, 'top')}px`,
                    height: '2px',
                    backgroundColor: 'var(--editor-primary-color, #0D61F2)',
                  }"
                ></div>
                <!-- 下边距线（等高线，横跨整个宽度） -->
                <div
                  class="margin-line margin-bottom"
                  :style="{
                    bottom: `${getPreviewOffset(option.margin.bottom, 'bottom')}px`,
                    height: '2px',
                    backgroundColor: 'var(--editor-primary-color, #0D61F2)',
                  }"
                ></div>
                <!-- 左边距线（等宽线，纵跨整个高度） -->
                <div
                  class="margin-line margin-left"
                  :style="{
                    left: `${getPreviewOffset(option.margin.left, 'left')}px`,
                    width: '2px',
                    backgroundColor: 'var(--editor-primary-color, #0D61F2)',
                  }"
                ></div>
                <!-- 右边距线（等宽线，纵跨整个高度） -->
                <div
                  class="margin-line margin-right"
                  :style="{
                    right: `${getPreviewOffset(option.margin.right, 'right')}px`,
                    width: '2px',
                    backgroundColor: 'var(--editor-primary-color, #0D61F2)',
                  }"
                ></div>
              </div>
            </div>
            <!-- 选项信息 -->
            <div class="page-margin-info">
              <div class="margin-label">{{ option.label }}</div>
              <div class="margin-values">
                <div class="margin-row">
                  <span class="margin-value">上: {{ option.margin.top }}厘米</span>
                  <span class="margin-value">下: {{ option.margin.bottom }}厘米</span>
                </div>
                <div class="margin-row">
                  <span class="margin-value">左: {{ option.margin.left }}厘米</span>
                  <span class="margin-value">右: {{ option.margin.right }}厘米</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 自定义页边距按钮 -->
        <div class="page-margin-custom" @click="handleCustomMargin">
          <i class="i-ri-settings-3-line"></i>
          <span>自定义页边距</span>
        </div>
      </div>
    </template>
  </ToolbarButton>

  <!-- 页面设置弹窗 -->
  <PageSettings
    v-model="showPageSettings"
    :page-sizes="editorProps?.dicts?.pageSizes"
    default-tab="margin"
  />
</template>

<script setup lang="ts">
import { inject, computed, ref, type Ref } from "vue";
import type { PageOption, EditorProps } from "../../../../types";
import ToolbarButton from "../../../button/index.vue";
import { PAGE_MARGIN_OPTIONS } from "../../../../config/constants";
import PageSettings from "./PageSettings.vue";
import { closeAllToolbarPopups } from "../../../button/src/utils/toolbarPopupManager";

defineOptions({
  name: "PageMargin",
});

const props = withDefaults(
  defineProps<{
    largeIcon?: boolean;
    hideText?: boolean;
  }>(),
  {
    largeIcon: false,
    hideText: true,
  }
);

// 注入页面配置和编辑器配置
const pageOptions = inject<Ref<PageOption>>("page");
const editorProps = inject<EditorProps>("editorProps");

// 页面设置弹窗显示状态
const showPageSettings = ref(false);

// 页边距预设选项（从配置中获取）
const marginOptions = PAGE_MARGIN_OPTIONS;

// 检查当前页边距是否匹配某个预设选项
const isMarginEqual = (
  margin1: { top: number; bottom: number; left: number; right: number },
  margin2: { top: number; bottom: number; left: number; right: number }
) => {
  return (
    Math.abs(margin1.top - margin2.top) < 0.01 &&
    Math.abs(margin1.bottom - margin2.bottom) < 0.01 &&
    Math.abs(margin1.left - margin2.left) < 0.01 &&
    Math.abs(margin1.right - margin2.right) < 0.01
  );
};

// 当前选中的页边距选项
const currentMarginOption = computed(() => {
  if (!pageOptions?.value?.margin) return null;
  const currentMargin = {
    top: pageOptions.value.margin.top,
    bottom: pageOptions.value.margin.bottom,
    left: pageOptions.value.margin.left,
    right: pageOptions.value.margin.right,
  };
  return marginOptions.find((option) =>
    isMarginEqual(option.margin, currentMargin)
  );
});

// 计算预览尺寸（将cm转换为px，用于预览）
const getPreviewOffset = (cm: number, direction: 'top' | 'bottom' | 'left' | 'right') => {
  const frameWidth = 56 - 2;
  const frameHeight = 72 - 2;
  
  if (direction === 'top' || direction === 'bottom') {
    return Math.max((cm / 35) * frameHeight, 2);
  } else {
    return Math.max((cm / 29) * frameWidth, 2);
  }
};

// 切换页边距（主按钮点击）
const togglePageMargin = () => {
};

// 设置页边距
const setPageMargin = (margin: {
  top: number;
  bottom: number;
  left: number;
  right: number;
}) => {
  if (!pageOptions?.value) return;

  pageOptions.value.margin = {
    ...pageOptions.value.margin,
    ...margin,
  };
  
  // 关闭 dropdown 弹窗
  closeAllToolbarPopups(undefined, undefined, ["select", "popover"]);
};

const handleCustomMargin = () => {
  // 关闭 dropdown 弹窗
  closeAllToolbarPopups(undefined, undefined, ["select", "popover"]);
  // 打开页面设置弹窗
  showPageSettings.value = true;
};
</script>

<style lang="scss" scoped>
.page-margin-dropdown {
  padding: 12px;
  background-color: var(--editor-color-white);
}

.page-margin-options {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.page-margin-option {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 10px;
  border: 1px solid var(--editor-border-color);
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
  background-color: var(--editor-color-white);

  &:hover {
    background-color: color-mix(
      in srgb,
      var(--editor-primary-color) 4%,
      transparent
    );
  }

  &.active {
    background-color: color-mix(
      in srgb,
      var(--editor-primary-color) 8%,
      transparent
    );
  }
}

.page-margin-check {
  flex-shrink: 0;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .i-ri-check-line {
    font-size: 18px;
    color: var(--editor-primary-color, #0D61F2);
    transition: color 0.2s ease;
  }
}

.page-margin-preview {
  flex-shrink: 0;
  width: 56px;
  height: 72px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 4px;
}

.preview-frame {
  width: 100%;
  height: 100%;
  background-color: #ffffff;
  border: 1px solid #454D5A;
  border-radius: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  position: relative;
}

.preview-container {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}


.margin-line {
  flex-shrink: 0;
  background-color: var(--editor-primary-color, #0D61F2);
  border-radius: 0;
  position: absolute;
}

.margin-top {
  top: 0;
  left: 0;
  width: 100%;
  height: 2px;
}

.margin-bottom {
  bottom: 0;
  left: 0;
  width: 100%;
  height: 2px;
}

.margin-left {
  top: 0;
  left: 0;
  width: 2px;
  height: 100%;
}

.margin-right {
  top: 0;
  right: 0;
  width: 2px;
  height: 100%;
}

.page-margin-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 6px;
  min-width: 0;
}

.margin-label {
  font-size: 14px;
  font-weight: 700;
  color: var(--editor-text-color);
  line-height: 1.2;
}

.margin-values {
  display: flex;
  flex-direction: column;
  gap: 4px;
  font-size: 12px;
  color: var(--editor-text-color-light);
}

.margin-row {
  display: flex;
  gap: 12px;
  line-height: 1.4;
}

.margin-value {
  white-space: nowrap;
}

.page-margin-custom {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px;
  margin-top: 8px;
  border-top: 1px solid var(--editor-border-color);
  cursor: pointer;
  transition: all 0.2s ease;
  color: var(--editor-text-color);

  i {
    font-size: 16px;
    color: var(--editor-text-color);
    transition: color 0.2s ease;
  }

  span {
    font-size: 14px;
  }

  &:hover {
    background-color: color-mix(
      in srgb,
      var(--editor-primary-color) 4%,
      transparent
    );
    color: var(--editor-primary-color);

    i {
      color: var(--editor-primary-color);
    }
  }
}

/* 暗色主题适配 */
[theme-mode="dark"] {
  .page-margin-dropdown {
    background-color: var(--editor-color-dark);
  }

  .page-margin-option {
    background-color: var(--editor-color-dark);
    border-color: var(--editor-border-color);

    &:hover {
      background-color: color-mix(
        in srgb,
        var(--editor-primary-color) 4%,
        transparent
      );
    }
  }

  .preview-frame {
    background-color: #1a1a1a;
    border-color: var(--editor-border-color);
  }

  .page-margin-custom {
    color: var(--editor-text-color);
    border-color: var(--editor-border-color);

    i {
      color: var(--editor-text-color);
    }

    &:hover {
      background-color: color-mix(
        in srgb,
        var(--editor-primary-color) 4%,
        transparent
      );
      color: var(--editor-primary-color);

      i {
        color: var(--editor-primary-color);
      }
    }
  }
}
</style>

